from flask import Blueprint, request, render_template, jsonify
from sqlalchemy import desc
from applications.common.utils.http import table_api
from applications.common.utils.rights import authorize
from applications.extensions import db
from applications.extensions.init_tasks import tb_jyxt_notice, tb_spt_notice, tb_check_notice, tb_spt_land
from applications.models import AdminLog, JyxtNotice, JyxtLand
from applications.schemas import LogOutSchema
from applications.common.curd import model_to_dicts

bp = Blueprint('spt_info', __name__, url_prefix='/nx_spt')


# 日志管理
@bp.get('/')
@authorize("system:log:main")
def index():
    return render_template('system/admin_log/main.html')


# 登录日志
@bp.get('/loginLog')
@authorize("system:log:main")
def login_log():
    # orm查询
    # 使用分页获取data需要.items
    log = AdminLog.query.filter_by(url='/passport/login').order_by(desc(AdminLog.create_time)).layui_paginate()
    count = log.total
    return table_api(data=model_to_dicts(schema=LogOutSchema, data=log.items), count=count)


# 操作日志
@bp.get('/operateLog')
@authorize("system:log:main")
def operate_log():
    # orm查询
    # 使用分页获取data需要.items
    log = AdminLog.query.filter(
        AdminLog.url != '/passport/login').order_by(
        desc(AdminLog.create_time)).layui_paginate()
    count = log.total
    return table_api(data=model_to_dicts(schema=LogOutSchema, data=log.items), count=count)


@bp.route('/check_notice')  # 手动检测公共同步情况
@authorize("system:notice:query", log=True)
def check_notice():
    tb_jyxt_notice()
    tb_spt_notice()
    tb_check_notice()
    return '检测公共信息同步情况成功!'


@bp.route('/update_notice_sfts/<GGID>')
def update_notice_sfts(GGID):
    if not GGID:
        return "请输入公告ID"
    notice = JyxtNotice.query.filter(JyxtNotice.GGID == GGID).first()
    if not notice:
        return "公告ID不存在"
    else:
        notice.sfts = 1
        db.session.commit()
        return jsonify(notice)


@bp.route('/update_spt_land')  # 获取公共资源交易服务平台成交的宗地信息
def update_spt_land_info():
    tb_spt_land()
    return '更新湖北省公共资源交易平台成交公示信息成功!'